package com.oschina.sequence;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.oschina.sequence.exception.SequenceException;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by limu on 16/6/28.
 */
public class DbPoolManger {
    /**
     * 数据库连接池map
     */
    private static Map<Integer, DruidDataSource> dataSourceMap = new HashMap<>();

    /**
     * 获取连接
     *
     * @param dbIndex dbIndex
     * @return
     * @throws SequenceException
     */
    public static Connection getConnection(int dbIndex) throws SequenceException {
        try {
            return dataSourceMap.get(dbIndex).getConnection();
        } catch (Throwable e) {
            throw new SequenceException("getConnection error", e);
        }
    }

    /**
     * 初始化线程池
     *
     * @param databaseConfigs databaseConfigs
     * @return
     * @throws Exception
     */
    public static void init(List<DatabaseConfig> databaseConfigs) throws SequenceException {
        int count = 0;
        for (DatabaseConfig databaseConfig : databaseConfigs) {
            DruidDataSource dataSource = new DruidDataSource();

            try {
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl(databaseConfig.getJdbcUrl());
                dataSource.setUsername(databaseConfig.getUserName());
                dataSource.setPassword(databaseConfig.getPassword());

                //初始化连接池中的连接数
                dataSource.setInitialSize(3);

                //连接池中保留的最小连接数
                dataSource.setMinIdle(3);

                //连接池中保留的最大连接数
                dataSource.setMaxActive(10);

                //每隔60s检测一次连接, 空闲的时候
                dataSource.setTestWhileIdle(true);
                dataSource.setValidationQuery("select name from sequence0");

                //sql监控
                dataSource.setFilters("stat");

                //初始化
                dataSource.init();
            } catch (Throwable e) {
                throw new SequenceException("db pool init error, databaseConfigs=" + JSON.toJSONString(databaseConfigs), e);
            }

            dataSourceMap.put(count, dataSource);
            count++;
        }
    }

    /**
     * 销毁连接池
     *
     * @throws SequenceException
     */
    public static void destroy() throws SequenceException {
        try {
            for (Map.Entry<Integer, DruidDataSource> entry : dataSourceMap.entrySet()) {
                DruidDataSource dataSource = entry.getValue();
                dataSource.close();
            }
        } catch (Throwable e) {
            throw new SequenceException("dataSource destroy error", e);
        }
    }

}
